package com.example.treehole;

import android.Manifest;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.util.Log;
import android.view.View;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.baidu.location.LocationClient;
import com.example.treehole.base.BaseBindingActivity;
import com.example.treehole.bean.User;
import com.example.treehole.databinding.ActivityLoginBinding;
import com.example.treehole.databinding.DialogEditPassword2Binding;
import com.example.treehole.util.Api;
import com.example.treehole.util.HttpUtil;
import com.example.treehole.util.PasswordManager;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class LoginActivity extends BaseBindingActivity<ActivityLoginBinding> {

    @Override
    protected void initListener() {
        viewBinder.goRegisterBtn.setOnClickListener(v -> startActivity(new Intent(LoginActivity.this, RegisterActivity.class)));
        viewBinder.tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!viewBinder.cbAgree.isChecked()) {
                    toast("请先同意《服务条款》和《隐私协议》");
                    return;
                }
                String phone = viewBinder.etPhone.getText().toString();
                String password = viewBinder.etPassword.getText().toString();
                if (phone.isEmpty()) {
                    toast("请输入账号");
                    return;
                }
                if (password.isEmpty()) {
                    toast("请输入密码");
                    return;
                }
                showLoading();
                HashMap<String, Object> params = new HashMap<>();
                params.put("phone", phone);
                params.put("password", password);
                HttpUtil.getModel(Api.LOGIN, params, User.class, new HttpUtil.OnNetModelListener<User>() {
                    @Override
                    public void success(User data, String message) {
                        dismissLoading();
                        if (viewBinder.cbRememberPassword.isChecked()) {
                            PasswordManager.saveUsername(LoginActivity.this, phone);
                            PasswordManager.savePassword(LoginActivity.this, password);
                        } else {
                            PasswordManager.clearUsername(LoginActivity.this);
                            PasswordManager.clearPassword(LoginActivity.this);
                        }
                        App.login(data);
                        startActivity(MainActivity.class);
                        toast(message);
                        finish();

                    }

                    @Override
                    public void error(String error) {
                        dismissLoading();
                        toast(error);
                    }
                });

            }
        });
        viewBinder.tvForget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showEditPasswordDialog();
            }
        });
    }


    private void showEditPasswordDialog() {
        DialogEditPassword2Binding binding = DialogEditPassword2Binding.inflate(getLayoutInflater());
        AlertDialog alertDialog = new AlertDialog.Builder(this).setView(binding.getRoot()).show();
        binding.tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String phone = binding.etPhone.getText().toString();
                String email = binding.etEmail.getText().toString();
                String newPassword = binding.etNewPassword.getText().toString();
                if (phone.isEmpty()) {
                    toast("请输入账号");
                    return;
                }
                if (email.isEmpty()) {
                    toast("请输入邮箱");
                    return;
                }
                if (newPassword.isEmpty()) {
                    toast("请输入新密码");
                    return;
                }
                alertDialog.dismiss();
                User user = new User();
                user.phone = phone;
                user.email = email;
                user.password = newPassword;
                doUpdatePassword(user);
            }
        });
        binding.tvCancel.setOnClickListener(v -> alertDialog.dismiss());
    }

    private void doUpdatePassword(User user) {
        showLoading();
        HttpUtil.post(Api.USER_UPDATE_PASSWORD, HttpUtil.toJSON(user), new HttpUtil.OnNetStringListener() {
            @Override
            public void success(String data, String message) {
                display$Toast(message);

            }

            @Override
            public void error(String message) {
                display$Toast(message);
            }
        });
    }

    @Override
    protected void initData() {
        String password = PasswordManager.getPassword(this);
        String username = PasswordManager.getUsername(this);
        if (!username.isEmpty() && !password.isEmpty()) {
            viewBinder.cbRememberPassword.setChecked(true);
            viewBinder.etPhone.setText(username);
            viewBinder.etPassword.setText(password);
        }
        requestPermission();
    }

    private void requestPermission() {

        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            Log.d("TAG", "onCreate: " + Arrays.toString(permissions));
            ActivityCompat.requestPermissions(this, permissions, 1);
        }
    }
}